package com.rui.mq.rocketmq.order;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.List;

public class Producer {

    public static void main(String[] args) throws MQClientException, MQBrokerException, RemotingException, InterruptedException {
        DefaultMQProducer producer = new DefaultMQProducer("group1");
        producer.setNamesrvAddr("192.168.10.129:9876;192.168.10.129:9877");
        producer.setVipChannelEnabled(false);
        producer.setSendMsgTimeout(10000);
        producer.start();
        List<OrderStep> orderSteps = OrderStep.buildOrders();
        for(int i = 0 ; i < orderSteps.size() ; i++){
            String body = orderSteps.get(i) + "";
            Message message = new Message("OrderTopic","Order","i" + i,body.getBytes());
            SendResult sendResult = producer.send(message, new MessageQueueSelector() {
                @Override
                public MessageQueue select(List<MessageQueue> list, Message message, Object o) {
                    long orderId = (long) o;
                    long index = orderId % list.size();
                    return list.get((int) index);
                }
            }, orderSteps.get(i).getOrderId());
            System.out.println("发送结果" + sendResult);
        }
        producer.shutdown();
    }
}
